//
//  SWTodayViewController.swift
//  ChildStory
//
//  Created by linhan on 2016/12/6.
//  Copyright © 2016年 Aiya. All rights reserved.
//

import Foundation
import UIKit
class SWTodayViewController: SWBaseViewController,ScrollADImageDelagate,ClickActionDelegate,SWAPIComponent,NullDataStatusProtocol,SWGlobalPopupMenu
{
    var nullDataView:UIView?
    var popupMenuController:AnyObject?
    
    //整体左边距
    private let LeftMargin:CGFloat = 15
    //整体右边距
    private let RightMargin:CGFloat = 15
    //区块与区块的间距
    private let Grid:CGFloat = 8
    
    private var _musics:[SWMusic] = []
    private var _poetries:[SWPoetry] = []
    private var _banners:[SWBanner] = []
    
    
    private var _scrollADImage:ScrollADImage?
    lazy private var _container:UIScrollView = UIScrollView()
    lazy private var _pageControl:UIPageControl = UIPageControl()
    lazy private var _statusLabel:UILabel = UILabel()
    private var _musicsView:SWTodayMusicsView?
    private var _poetriesView:SWTodayPoetriesView?
    
    deinit
    {
        NotificationCenter.default.removeObserver(self)
        trace("DEINIT SWTodayViewController")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setup()
    }
    
    private func setup()
    {
        automaticallyAdjustsScrollViewInsets = false
        view.backgroundColor = UIColor(hex: 0xf5f5f5)
        
        nullDataViewSetup()
        
        
        _container.frame = view.bounds
        _container.alwaysBounceVertical = true
        _container.alpha = 0
        _container.contentInset = UIEdgeInsetsMake(navigationBarBottom, 0, 0, 0)
        //_container.mj_header = header
        view.addSubview(_container)
        
        //滚动banner广告
        var bottom:CGFloat = 0
        bottom = createBanner(y:0)
        //宝宝信息栏
        bottom = createStatusView(y:bottom)
        //音乐
        createMusicsView(y:bottom)
        //诗歌
        createPoetriesView()
        
        SWNotificationCenter.addObserver(self, selector: #selector(childAccountInfoChangedNotification), name: NotificationName.ChildAccountInfoChanged, object: nil)
        
        reloadData()
        setupRefreshControl()
        globalPopupMenuSetup(container: view)
        statusViewUpdate()
    }
    
    private func nullDataViewSetup()
    {
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(nullDataViewTapped))
        setupNullDataView(withText: "加载失败，点击重试", container: view)
        nullDataView?.isUserInteractionEnabled = true
        nullDataView?.addGestureRecognizer(tapGesture)
    }
    
    private func setupRefreshControl()
    {
        let header:MJRefreshNormalHeader = MJRefreshNormalHeader(refreshingBlock: {[weak self] in
            self?.reloadData()
        })
        header.lastUpdatedTimeLabel?.isHidden = true
        header.beginRefreshing()
        _container.mj_header = header
    }
    
    private func endRefreshing()
    {
        _container.mj_header?.endRefreshing()
    }
    
    //
    private func createBanner(y:CGFloat) -> CGFloat
    {
        let bannerHeight:CGFloat = view.width * 0.4613
        let bannerContainer:UIView = UIView()
        bannerContainer.frame = CGRectMake(0, y, view.width, bannerHeight)
        _container.addSubview(bannerContainer)
        
        let bannerRect = CGRectMake(0, 0, view.width, bannerHeight)
        _scrollADImage = ScrollADImage(frame: bannerRect)
        _scrollADImage?.delegate = self
        _scrollADImage?.autoScrollInterval = 6
        _scrollADImage?.backgroundColor = UIColor.white
        bannerContainer.addSubview(_scrollADImage!)
        
        _pageControl.backgroundColor = UIColor.clear
        _pageControl.currentPageIndicatorTintColor = UIColor(hex: 0xffaabc)
        _pageControl.isUserInteractionEnabled = false
        bannerContainer.addSubview(_pageControl)
        _pageControl.currentPage = 0
        
        return bannerContainer.bottom
    }
    
    private func createStatusView(y:CGFloat) -> CGFloat
    {
        let statusView = UIView()
        statusView.frame = CGRectMake(0, y, view.width, 50)
        statusView.backgroundColor = UIColor(hex:0xf8e9eb)
        _container.addSubview(statusView)
        
        _statusLabel.textColor = UIColor(hex: 0x2f3231)
        _statusLabel.font = UIFont.systemFont(ofSize: 18)
        _statusLabel.frame = CGRectMake(LeftMargin, 0, view.width - LeftMargin - RightMargin, statusView.height)
        statusView.addSubview(_statusLabel)
        
        return statusView.bottom
    }
    
    private func createMusicsView(y:CGFloat)
    {
        let musicsView = SWTodayMusicsView(frame:CGRectMake(0, y, view.width, 0))
        musicsView.delegate = self
        _container.addSubview(musicsView)
        _musicsView = musicsView
    }
    
    private func createPoetriesView()
    {
        let poetriesView = SWTodayPoetriesView(frame:CGRectMake(0, 0, view.width, 0))
        poetriesView.delegate = self
        _container.addSubview(poetriesView)
        _poetriesView = poetriesView
    }
    
    private func reloadData()
    {
        fetchTodayData()
    }
    
    private func fetchTodayData()
    {
        let req = SWTodayContentFetchReq()
        req.successCallback = {[weak self] response,_ in
            if let response = response as? SWTodayContentFetchRsp
            {
                if let aBanners = response.banners,aBanners.count > 0
                {
                    self?._banners = aBanners.flatMap({SWBanner(response:$0)})
                }
                
                if let aMusics = response.musics,aMusics.count > 0
                {
                    let musics:[SWMusic] = aMusics.flatMap({SWMusic(response: $0)})
                    self?._musics = musics
                    self?._musicsView?.musics = musics
                }
                
                if let aPoetries = response.poetries,aPoetries.count > 0
                {
                    let poetries:[SWPoetry] = aPoetries.flatMap({SWPoetry(response: $0)})
                    self?._poetries = poetries
                    self?._poetriesView?.poetries = poetries
                }
                
                self?.updateScrollSubView()
                self?.endRefreshing()
            }
            else
            {
                self?.loadFail()
            }
            
        }
        req.failCallback = {[weak self] error in
            self?.loadFail()
        }
        load(req)
    }
    
    private func loadFail()
    {
        endRefreshing()
        setNullDataViewHidden(false)
    }
    
    private func statusViewUpdate()
    {
        let days:String = SWAccountManager.sharedManager().account?.child?.daysString ?? ""
        _statusLabel.text = "宝宝\(days)了"
    }
    
    private func updateScrollSubView()
    {
        let images:[String] = _banners.map({$0.imageURL ?? ""})
        _scrollADImage?.images = images
        _pageControl.numberOfPages = images.count
        _pageControl.sizeToFit()
        _pageControl.center = CGPointMake(view.width * 0.5, (_pageControl.superview?.height ?? 0) - 30)
        
        _poetriesView?.y = (_musicsView?.bottom ?? 0) + Grid
        _container.contentSize = CGSizeMake(view.width, _poetriesView?.bottom ?? 0)
        appearContainer()
    }
    
    private var _intervalID:String = ""
    private func appearContainer()
    {
        clearTimeout(_intervalID)
        _intervalID = setTimeout(0.2, closure: {
            UIView.animate(withDuration: 0.15, animations: {
                self._container.alpha = 1
            })
        })
    }
    
    func view(_ view:UIView, click action:String, argument aArgument:[AnyHashable:Any]?)
    {
        if action == CallbackAction.Tap
        {
            let index:Int = aArgument?[SWKey.index] as? Int ?? 0
            if view is SWTodayMusicsView
            {
                let viewController = SWEventMusicViewController()
                viewController.musics = _musics
                viewController.index = index
                navigationController?.pushViewController(viewController, animated: true)
            }
            else if view is SWTodayPoetriesView
            {
                let viewController = SWPoetryPagesViewController()
                viewController.poetries = _poetries
                viewController.targetIndex = index
                navigationController?.pushViewController(viewController, animated: true)
            }
        }
        if action == CallbackAction.More
        {
            if view is SWTodayMusicsView
            {
                let viewController = SWMusicsListViewController()
                navigationController?.pushViewController(viewController, animated: true)
            }
            else if view is SWTodayPoetriesView
            {
                let viewController = SWPoetriesListViewController()
                navigationController?.pushViewController(viewController, animated: true)
            }
        }
    }
    
    func scrollADImage(_ scrollADImage: ScrollADImage, didScrollToIndex index: Int)
    {
        _pageControl.currentPage = index
    }
    
    func scrollADImage(_ scrollADImage: ScrollADImage, didSelectIndex index: Int)
    {
        if let url = _banners.valueAt(index)?.contentURL
        {
            let viewController = SWNewsViewController(url: "https://mp.weixin.qq.com/s/N2j-st8QA2SKUetvgJ5QwA")
            viewController.title = "咿呀说"
            navigationController?.pushViewController(viewController, animated: true)
        }
    }
    
    @objc private func nullDataViewTapped()
    {
        reloadData()
    }
    
    @objc private func childAccountInfoChangedNotification()
    {
        statusViewUpdate()
    }
    
}
